﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Elasticsearch;

namespace ED.Serilog
{
    public static class SerilogExtensions
    {
        public static void AddSerilog(this WebApplicationBuilder build)
        {
            SerilogConfig serilogConfig = new SerilogConfig();
            build.Configuration.GetSection("ESConfig").Bind(serilogConfig);
            // 配置Serilog
            var Logger = new LoggerConfiguration()
                // .MinimumLevel.Override("Microsoft", LogEventLevel.Information) // 排除Microsoft的日志
                .Enrich.FromLogContext() // 注册日志上下文
                .WriteTo.Console(LogEventLevel.Information) // 输出到控制台
                                                            // .WriteTo.MySQL(connectionString: builder.Configuration.GetConnectionString("DbConnectionString"), tableName: "Logs") // 输出到数据库
                 .WriteTo.Logger(configure => configure // 输出到文件
                            .MinimumLevel.Debug()
                            .WriteTo.File(  //单个日志文件，总日志，所有日志存到这里面
                                $"logs\\log.txt",
                                rollingInterval: RollingInterval.Day,
                                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
                            .WriteTo.RollingFile( //每天生成一个新的日志，按天来存日志
                                "logs\\{Date}-log.txt", //定输出到滚动日志文件中，每天会创建一个新的日志，按天来存日志
                                retainedFileCountLimit: 7,
                                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
                            ));
            if (serilogConfig.IsActiveES)
            {
                Logger.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(serilogConfig.ESUrl)
                {
                    AutoRegisterTemplate = true,
                    IndexFormat = "ED-{0:yyyy.MM.dd}",
                    MinimumLogEventLevel = LogEventLevel.Information,
                    BatchPostingLimit = 50,
                    Period = TimeSpan.FromSeconds(2),
                    //ModifyConnectionSettings = conn =>
                    //{
                    //    // 设置ES的账户密码
                    //    return conn.BasicAuthentication("username", "password");
                    //}
                });
            }
            Logger.CreateLogger();
            build.Host.UseSerilog(); // Register Serilog with the Host
        }
    }
}